package com.atguigu.day10;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;

public class Flink01_SQL_UDF_ScalarFun {
    public static void main(String[] args) {
        //1.获取流的执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        //2.从端口读取数据并转为WaterSensor
        SingleOutputStreamOperator<WaterSensor> waterSensorStream = env.socketTextStream("localhost", 9999)
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        String[] split = value.split(",");
                        return new WaterSensor(split[0], Long.parseLong(split[1]), Integer.parseInt(split[2]));
                    }
                });

        //3.获取表的执行环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        //4.将流转为表
        Table table = tableEnv.fromDataStream(waterSensorStream);

        //5.不注册直接在TableAPI中使用
       /* table.select($("id"), call(MyIdlen.class, $("id")).as("IdLen"))
                .execute()
                .print();*/

       //先注册然后在TableAPI中使用
        tableEnv.createTemporarySystemFunction("idLen", MyIdlen.class);
         /*table.select($("id"), call("idLen", $("id")).as("IdLen"))
                .execute()
                .print();*/

         //在SQL中使用 一定要先注册
        tableEnv.executeSql("select id,idLen(id) as IdLen from "+table).print();



    }

    //自定义一个类继承ScalarFun 通过这个函数，获取id的字符串长度
    public static class MyIdlen extends ScalarFunction{
        public int eval(String value){
            return value.length();
        }
    }

}
